package me.eleme.anubis.openapi.oauth.impl;




import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import me.eleme.anubis.openapi.api.entity.base.BaseBizResponse;
import me.eleme.anubis.openapi.api.exception.ServerErrorException;
import me.eleme.anubis.openapi.api.exception.ServiceException;
import me.eleme.anubis.openapi.config.Config;
import me.eleme.anubis.openapi.config.Constants;
import me.eleme.anubis.openapi.config.oauth.response.ErrorResponse;
import me.eleme.anubis.openapi.oauth.IoauthClient;
import me.eleme.anubis.openapi.oauth.OauthRequest;
import me.eleme.anubis.openapi.utils.StringUtils;
import me.eleme.anubis.openapi.utils.WebUtils;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * 客户端模式获取Token
 * @author liuzhiyong
 */
@Slf4j
public class DefaultOauthClient implements IoauthClient {
    /**
     * 默认连接超时时间为15秒
     */
    private final int connectTimeout = 15000;
    /**
     * 默认响应超时时间为30秒
     */
    private final int readTimeout = 30000;
    private final String serverHostUrl;
    private final Config context;

    public DefaultOauthClient(Config context, String suffix) {
        this.context = context;
        this.serverHostUrl = context.getOauthApiUrl() + suffix;
    }

    @Override
    public <T> T execute(OauthRequest request, Type type) throws ServiceException{
        try {
            String respJson = WebUtils.doPost(context, serverHostUrl,
                    request.getBodyMap(),
                    Constants.CHARSET_UTF8,
                    WebUtils.getReqId(),
                    connectTimeout,
                    readTimeout,
                    request.getHeaderMap()
            );
            log.debug("响应结果:{}",respJson);
            // 构建响应解释器
            BaseBizResponse bizResponse = JSON.parseObject(respJson, BaseBizResponse.class);
            if (bizResponse != null && !Constants.SUCCESS_CODE.equals(bizResponse.getCode())) {
                ServiceException serviceException = toException(bizResponse);
                if (serviceException != null) {
                    throw serviceException;
                }
                throw new ServerErrorException();
            }
            if (type == void.class) {
                return null;
            }
            String s2 = bizResponse.getBusinessData();
            return JSON.parseObject(s2,type);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static ServiceException toException(BaseBizResponse error) throws ServiceException {
        String code = error.getCode();
        if(StringUtils.isEmpty(code)) {
            return null;
        }
        String message = error.getMsg();
        return new ServiceException(message);
    }
}
